package com.project.design.algorithm;

import java.util.Arrays;

/**
 * 归并排序
 */
public class MergeSort {

    public void mergeSort(Integer[] str) {
        Integer[] temp = new Integer[str.length];
        mergeSort(str, 0, str.length - 1, temp);
    }

    private void mergeSort(Integer[] str, int left, int right, Integer[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            mergeSort(str, left, mid, temp);
            mergeSort(str, mid + 1, right, temp);
            merge(str, left, mid, right, temp);
        }
    }

    private static void merge(Integer[] str, int left, int mid, int right, Integer[] temp) {
        int i = left;
        int j = mid + 1;
        int t = 0;
        while (i <= mid && j <= right) {
            if (str[i] <= str[j]) {
                temp[t++] = str[i++];
            } else {
                temp[t++] = str[j++];
            }
        }
        while (i <= mid) {
            temp[t++] = str[i++];
        }
        while (j <= right) {
            temp[t++] = str[j++];
        }
        t = 0;
        while (left <= right) {
            str[left++] = temp[t++];
        }
        System.out.println(Arrays.toString(str));

    }
}
